package com.heima.search.listener;

import com.heima.common.util.JsonUtils;
import com.heima.search.service.ApArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

import static com.heima.common.constants.message.WmNewsUpDownConstants.WM_NEWS_UP_OR_DOWN_TOPIC;

@Slf4j
@Component
public class ArticleUpDownListener {

    @Autowired
    private ApArticleSearchService articleSearchService;

    @KafkaListener(topics = WM_NEWS_UP_OR_DOWN_TOPIC)
    public void receiveMsg(ConsumerRecord<?,?> record){
        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
        if(optional.isPresent()){
            //获取消息内容
            Object value = record.value();
            //解析成map集合
            Map<String, Integer> map = JsonUtils.toMap(value.toString(), String.class, Integer.class);

            //上下架时，同步操作索引库文章数据
            //            调用方法修改 isDown状态 ， 0-下架 ，1-上架
            articleSearchService.ArticleUpDown(map.get("articleId"),map.get("enable"));
        }
    }
}
